﻿using System;
using System.IO;
using System.Text;

namespace GeneratorModels.Utility
{
    internal class Log
    {
        private static readonly object obj = new object();
        private static readonly string path = AppDomain.CurrentDomain.BaseDirectory;

        static Log()
        {
            path = AppDomain.CurrentDomain.BaseDirectory + "log";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        ///     操作日志
        /// </summary>
        internal static void Info(string content)
        {
            WriteLogs("I", content);
        }

        /// <summary>
        ///     操作日志
        /// </summary>
        internal static void InfoFormat(string format, params object[] args)
        {
            WriteLogs("I", string.Format(format, args));
        }

        /// <summary>
        ///     错误日志
        /// </summary>
        internal static void Error(string content)
        {
            WriteLogs("E", content);
        }

        /// <summary>
        ///     错误日志
        /// </summary>
        internal static void ErrorFormat(string format, params object[] args)
        {
            WriteLogs("E", string.Format(format, args));
        }

        private static void WriteLogs(string type, string content)
        {
            lock (obj)
            {
                if (!string.IsNullOrEmpty(path))
                {
                    string file = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
                    if (!File.Exists(file))
                    {
                        FileStream fs = File.Create(file);
                        fs.Close();
                    }
                    if (File.Exists(file))
                    {
                        var sw = new StreamWriter(file, true, Encoding.UTF8);
                        sw.WriteLine("{0} - {1} - {2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), type, content);
                        sw.Close();
                    }
                }
            }
        }
    }
}